package com.fu.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 付大大
 * @description
 * @create 2021-01-24 17:25
 */
@WebServlet("/servletDemo08")
public class ServletDemo08 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String realPath = getServletContext().getRealPath("/img/hm.png");
        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(realPath));
        /*设置相应头支持的类型
        * Content-Type 消息头名称 支持的类型
        * application/octet-stream 消息头参数 应用的类型为字节流
        */
        resp.setHeader("Content-Type","application/octet-stream");

        /*
        * Content-Disposition 消息头名称 处理的形式
        * attachment;filename=hm.png 消息头参数  附件形式进行处理 指定下载文件的名称
        */
        resp.setHeader("Content-Disposition", "attachment;filename=hm.png");

        ServletOutputStream outputStream = resp.getOutputStream();

        byte[] bytes = new byte[1024];
        int len;
        while ((len = bufferedInputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
        }
        bufferedInputStream.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
